package com.xpoint.backend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xpoint.backend.common.R;
import com.xpoint.backend.dto.DishDto;
import com.xpoint.backend.entity.Dish;
import com.xpoint.backend.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dish")
//菜品管理
public class DishController {
    @Autowired
    private DishService dishService;

    @Cacheable(value = "SetmealDtoByPage")
    @GetMapping("/page")
//    分页查询
    public R<Page> findPage(Long page,Long pageSize,String name){
        return dishService.findPage(page,pageSize,name);
    }

    //    删除一条或多条缓存
    @CacheEvict(value = {"dish","SetmealDtoByPage"},allEntries = true)
    @PostMapping
//    添加菜品
    public R<String> addDish(@RequestBody DishDto dishDto){
        return dishService.addDish(dishDto);
    }

    //    删除一条或多条缓存
    @CacheEvict(value = {"dish","SetmealDtoByPage"},allEntries = true)
    @PostMapping("/status/{status}")
//    批量启售、停售
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam("ids") List<Long> id){
//        因为是批量操作，前端传过来的id是json数据，所以用list接收。
        return dishService.updateDishStatus(status,id);
    }

    //    删除一条或多条缓存
    @CacheEvict(value = {"dish","SetmealDtoByPage"},allEntries = true)
    @DeleteMapping
//    批量删除
    public R<String> deleteBatchDish(@RequestParam("ids") List<Long> id){
        return dishService.deleteBatchByIds(id);
    }


    @GetMapping("/{id}")
//    根据id查询
    public R<DishDto> findDishById(@PathVariable Long id){
        return dishService.findByid(id);
    }

//    删除一条或多条缓存
    @CacheEvict(value = {"dish","SetmealDtoByPage"},allEntries = true)
    @PutMapping
//    修改菜品
    public R<String> updateDish(@RequestBody DishDto dishDto){
        return dishService.updateDish(dishDto);
    }

//    cache缓存，在方法执行前，spring先查看缓存中是否有数据，如果有数据，则直接返回缓存数据；
//    如果没有数据，就调用方法，并且将方法的返回值放到缓存当中
    @Cacheable(value = {"dish","SetmealDtoByPage"},key = "#dish.categoryId")
    @GetMapping("/list")
//    根据id查询分类
    public R<List<DishDto>> findCategoryById(Dish dish){
        return dishService.findCategoryById(dish);
    }
}
